package com.hottv.meeting.videomeeting.common;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.RemoteException;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.chinamobile.iot.onenet.edp.toolbox.EdpClient;
import com.droidlogic.app.SystemControlManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hottv.meeting.videomeeting.module.edp.data.ContentItem;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetInfo;
import com.hottv.meeting.videomeeting.module.edp.EDPUtils;
import com.hottv.meeting.videomeeting.module.edp.data.EdpMsgItem;
import com.hottv.meeting.videomeeting.module.edp.data.MeetingInfo;
import com.hottv.meeting.videomeeting.module.meeting.CHexConver;
import com.hottv.meeting.videomeeting.module.meeting.InfoAccessImpl;
import com.hottv.meeting.videomeeting.module.meeting.MeetingAPI;
import com.hottv.meeting.videomeeting.module.meeting.MeetingManager;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetingData;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetingMem;
import com.hottv.meeting.videomeeting.module.meeting.data.MemItemInfo;
import com.hottv.meeting.videomeeting.module.meeting.data.MemSelectInfo;
import com.hottv.meeting.videomeeting.module.white.DoCallback;
import com.hottv.meeting.videomeeting.module.white.WhiteAPI;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import okhttp3.Call;
import okhttp3.Response;

import static java.lang.Math.abs;

/**
 * Created by chengwenqiang on 2019/5/31.
 */

public class MeetingUtils {

    //请求权限
    public static boolean checkSelfPermission(Activity activity, String permission, int requestCode) {
//        Log.d(MeetingConfig.TAG,":" + permission + " :" + requestCode);
        if (ContextCompat.checkSelfPermission(activity.getApplicationContext(),
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity,
                    new String[]{permission},
                    requestCode);
            return false;
        }

        return true;
    }

    public static String getTime()
    {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        return date;
    }


    //白板
    public static String white_url = "";
    public static String white_uuid = "";
    public static String white_roomtoken = "";
    public static String white_minitoken = "";
    //存储
    public static String storage_url = "https://apiipvt.bmobpay.com/";
    //
    public static String storage_png_url = "";

    //视频
    public static String video_url = "";
    public static String video_channelId = "";


    //后期通过接口得到
    public static String getUnifykeys(Context context){
        String  deviceId = "";
        try {
            deviceId = InfoAccessImpl.getInstance(context).getInfoData(InfoAccessImpl.DEVICEID, "");
        }catch (RemoteException e)
        {
            e.printStackTrace();
        }
        return deviceId;
    }

    //后期通过接口得到
    public static String getHottvId(Context context){
        String  deviceId = "";
        try {
            deviceId = InfoAccessImpl.getInstance(context).getInfoData(InfoAccessImpl.HOTTV_ID, "");
        }catch (RemoteException e)
        {
            e.printStackTrace();
        }
        return deviceId;
    }

    //后期通过接口得到
    public static String getTokenStr(Context context){
        String  tokenStr = "";
        try {
            tokenStr = InfoAccessImpl.getInstance(context).getInfoData(InfoAccessImpl.TOKEN_ID, "");
        }catch (RemoteException e)
        {
            e.printStackTrace();
        }
        return tokenStr;
    }

    //3DESECB加密,key必须是长度大于等于 3*8 = 24 位哈
    public static String encryptThreeDESECB(String src, String key) throws Exception
    {
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, securekey);
        byte[] b=cipher.doFinal(src.getBytes());
        return CHexConver.bytesToHexString(b);
    }

    //3DESECB解密,key必须是长度大于等于 3*8 = 24 位哈
    public static String decryptThreeDESECB(String src, String key) throws Exception
    {
        byte[] bytesrc = CHexConver.hexStr2Bytes(src);
        //--解密的key
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);

        //--Chipher对象解密
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, securekey);
        byte[] retByte = cipher.doFinal(bytesrc);

        return new String(retByte);
    }

    public static String getSignature(String nonce,String userId,String hottv)
    {
        String src = nonce+"&"+userId+"&"+hottv;
        Log.i(MeetingConfig.TAG,src);
        String signature="";
        try{
            signature =  encryptThreeDESECB(src, MeetingAPI.BMOP_KEY);
        }catch (Exception e){
            e.printStackTrace();
        }
        return signature;
    }

//    public static MeetingData getMeetingData(Context context)
//    {
//        MeetingData data= new MeetingData();
//        data.userID = getUnifykeys(context);
//        data.timestamp = System.currentTimeMillis();
//        Random rd = new Random();
//        data.nonce = String.valueOf(rd.nextInt(9999)) ;
//        data.signature = getSignature(String.valueOf(data.nonce),data.userID,"HOTTV");
//        data.status = 0;
//        data.startTime = 0;
//        data.meetingId = data.userID+String.valueOf(data.nonce);
//
//        data.members.add(new MeetingMem("苏       总","13802882313"));
//        data.members.add(new MeetingMem("张  潮  州","13760289294"));
//        data.members.add(new MeetingMem("程  文  强","13802885322"));
//        data.members.add(new MeetingMem("钟  伟  开","15918611748"));
//        data.members.add(new MeetingMem("大学城电视","02061888888 "));
//        return  data;
//    }

    public static MeetingData getMeetingData(Context context)
    {
        MeetingData data= new MeetingData();
        data.userID = getHottvId(context);
        data.token = getTokenStr(context);
        data.timestamp = System.currentTimeMillis();
//        Random rd = new Random();
//        data.nonce = String.valueOf(rd.nextInt(9999)) ;
//        data.signature = getSignature(String.valueOf(data.nonce),data.userID,"HOTTV");
        data.status = 0;
        data.startTime = 0;
        data.meetingId = data.userID;
//        data.meetingId = data.userID+String.valueOf(data.nonce);

//        MeetInfo info = MeetingManager.getInstance().getMeetInfo();
//        for(int i=0;i<info.members.size();i++)
//        {
//            data.members.add(new MeetingMem(info.members.get(i).name,info.members.get(i).phone));
//
//        }
        return  data;
    }

    public static void getMeetingInfo(Context context,final DoCallback callback)
    {
        final MeetingData data = getMeetingData(context);
        MeetingAPI.getInstance().openMeeting(context, data, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.i(MeetingConfig.TAG,"getMeetingInfo IOException:");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strTemp = response.body().string();
                Log.i(MeetingConfig.TAG,"body:"+strTemp);
                JsonObject room = new Gson().fromJson(strTemp, JsonObject.class);
                JsonObject resp= room.getAsJsonObject("resp");
                int rscode = resp.get("rscode").getAsInt();
                if(rscode==0)
                {
                        if(resp.getAsJsonObject("white").get("url")!=null)
                           white_url =   resp.getAsJsonObject("white").get("url").getAsString();

                        white_uuid =   resp.getAsJsonObject("white").getAsJsonObject("params").get("uuid").getAsString();
                        white_roomtoken =   resp.getAsJsonObject("white").getAsJsonObject("params").get("roomtoken").getAsString();
                        WhiteAPI.sdkToken =   resp.getAsJsonObject("white").getAsJsonObject("params").get("minitoken").getAsString();

                        if(resp.getAsJsonObject("storage").get("url")!=null)
                            storage_png_url =   resp.getAsJsonObject("storage").get("url").getAsString();
                        if(resp.getAsJsonObject("video").get("url")!=null)
                            video_url =   resp.getAsJsonObject("video").get("url").getAsString();
                        video_channelId =   resp.getAsJsonObject("video").getAsJsonObject("params").get("channelId").getAsString();
                        if (callback != null) {
                            callback.onSuccess(data.meetingId);
                        }
                }
                else
                {
                    Log.e(MeetingConfig.TAG,""+resp.get("rsdesc").getAsString());
                }
            }
        });
    }

    public static void joinMeeting(Context context,String meetingId,final DoCallback callback)
    {
        String userId = getHottvId(context);
        String token = getTokenStr(context);
        long timestamp = System.currentTimeMillis();
        MeetingAPI.getInstance().joinMeeting(context, userId, token, timestamp, meetingId, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.i(MeetingConfig.TAG,"joinMeeting IOException:");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strTemp = response.body().string();
                Log.i(MeetingConfig.TAG,"body:"+strTemp);
                JsonObject room = new Gson().fromJson(strTemp, JsonObject.class);
                JsonObject resp= room.getAsJsonObject("resp");
                int rscode = resp.get("rscode").getAsInt();
                if(rscode==0)
                {
                    if(resp.getAsJsonObject("white").get("url")!=null)
                        white_url =   resp.getAsJsonObject("white").get("url").getAsString();

                    white_uuid =   resp.getAsJsonObject("white").getAsJsonObject("params").get("uuid").getAsString();
                    white_roomtoken =   resp.getAsJsonObject("white").getAsJsonObject("params").get("roomtoken").getAsString();
                    white_minitoken =   resp.getAsJsonObject("white").getAsJsonObject("params").get("minitoken").getAsString();

                    if(resp.getAsJsonObject("storage").get("url")!=null)
                        storage_png_url =   resp.getAsJsonObject("storage").get("url").getAsString();
                    if(resp.getAsJsonObject("video").get("url")!=null)
                        video_url =   resp.getAsJsonObject("video").get("url").getAsString();
                    video_channelId =   resp.getAsJsonObject("video").getAsJsonObject("params").get("channelId").getAsString();
                    if (callback != null) {
                        callback.onSuccess("");
                    }
                }
            }
        });
    }

    public static void sendToEDP(Context context,long deviceId,String from,String meetingId)
    {
        MeetingInfo info = new MeetingInfo();
        info.createTime = System.currentTimeMillis();
        info.fromUserName =from;
        info.msgId = System.currentTimeMillis();
        info.content.meetingId = meetingId;
        Gson gson = new Gson();
        String msgStr = gson.toJson(info);

//        EdpMsgItem msg = new EdpMsgItem();
//        msg.code = MeetingConfig.MSG_NO_CALL;
//        msg.data = msgStr;
//
//        String msgContent = gson.toJson(msg);
        Log.i(MeetingConfig.TAG,"send content:"+msgStr);
//        EdpClient.getInstance().pushData(deviceId,msgStr);

        //发送广播
        Intent intent = new Intent();
        //设置广播的名字（设置Action）
        intent.setAction("SENT_ONENET_ID_ACTION");
        //携带数据
        intent.putExtra("deviceId",deviceId);
        intent.putExtra("content",msgStr);
        //发送广播（无序广播）
        context.sendBroadcast(intent);

    }

//    //推送会议消息给参加会议成员
//    public static void pushMsgMeetingMem(String meetingId)
//    {
//        List<MemItemInfo> memList = MeetingManager.getInstance().getMemList();
//        long deviceId = Long.parseLong(EDPUtils.edp_devices_Id);
//        String fromName = MeetingManager.getInstance().getNameFromDeviceId(deviceId);
//        for(int i=0;i<memList.size();i++)
//        {
//            MemItemInfo info = memList.get(i);
//            if(info.deviceId!=0)
//            {
//                sendToEDP(info.deviceId,fromName,meetingId);
//            }
//        }
//    }

    public static void pushMsgMeetingMem(Context context,String meetingId)
    {
        MeetInfo info = MeetingManager.getInstance().getMeetInfo();

        long deviceIdFrom = Long.parseLong(EDPUtils.edp_devices_Id);
        String fromName = MeetingManager.getInstance().getNameFromDeviceId(deviceIdFrom);
        for(int i=0;i<info.members.size();i++)
        {
            MemSelectInfo mem = info.members.get(i);
            long deviceId = MeetingManager.getInstance().getDeviceIdFromPhone(mem.phone);
            if(deviceId!=0)
            {
                Log.i(MeetingConfig.TAG,"pushMsgMeetingMem "+deviceId);
                sendToEDP(context,deviceId,fromName,meetingId);
            }
        }
    }
}
